import axios from 'axios'
import qs from 'qs'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

service.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json;charset=utf-8'
    if (config.method === 'post') {
      config.params = undefined
    }
    if (typeof config.headers['Content-Type'] === 'string' && config.headers['Content-Type'].search('application/x-www-form-urlencoded') !== -1) {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  (error) => {
    return Promise.reject(error.response)
  }
)

service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return response
    }

    throw new Error(response.status.toString())
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service
